import { createRouter, createWebHistory } from 'vue-router'
import cache from '@/util/cache.js'
const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: '/register',
    component: () => import('@/views/register/register.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/views/home/index.vue'),
    children: []
  }
]

const router = createRouter({
  routes,
  history: createWebHistory()
})
//动态添加路由
// const navList = cache.getCache('jxcms-userNav')
// const routerList = []
// for (const key of navList) {
//   routerList.push({
//     path: `/home/${key.nUrl.split('/')[2]}`,
//     name: `${key.nUrl.split('/')[2].toUpperCase()}`,
//     component: modules[`..${key.nUrl}`]
//   })
// }
// for (const routerListElement of routerList) {
//   router.addRoute('Home', routerListElement)
// }

router.beforeEach((to, from, next) => {
  if (to.path === '/login' || to.path === '/register') {
    if (cache.getCache('jxcms-token')) {
      next('/roles')
    } else {
      next()
    }
  } else {
    if (cache.getCache('jxcms-token')) {
      next()
    } else {
      next('/login')
    }
  }
})
export default router
